<template>
    <div class="page-container">
      <div class="user-profile">
        <div class="user-stats">
          <div class="stat-item">
            <div class="stat-value">{{ stats.following || 0 }}</div>
            <div class="stat-label">关注</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ stats.followers || 0 }}</div>
            <div class="stat-label">粉丝</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ stats.likes || 0 }}</div>
            <div class="stat-label">获赞</div>
          </div>
        </div>
  
        <div class="register-info">
          注册时间：2019-07-06
        </div>
  
        <div class="recent-activities">
          <h3 class="section-title">最近动态</h3>
          <div class="activity-list">
            <div v-for="(activity, index) in activities" :key="index" class="activity-item">
              <div class="activity-content">
                在<span class="shop-name">{{ activity.shopName }}</span>{{ activity.action }}
              </div>
              <div class="activity-time">{{ activity.time }}</div>
            </div>
          </div>
          <div class="view-more">
            更多最近动态 »
          </div>
        </div>
  
        <div class="reviews-section" v-if="showReviewInput">
          <div class="review-input">
            <div class="shop-info">
              {{ currentShop }}
              <span class="status">(预览)</span>
            </div>
            <div class="review-textarea">
              <el-input
                v-model="reviewContent"
                type="textarea"
                :rows="3"
                placeholder="还记得这家店的特色吗？写下你的评价，分享体验"
              />
            </div>
          </div>
        </div>
      </div>
  
      <div class="review-container">
        <div class="review-header">
          <div class="shop-select">
            <el-select v-model="selectedShop" placeholder="选择要评价的店铺" class="shop-select-input" @change="handleShopSelect">
              <el-option
                v-for="shop in shopList"
                :key="shop.id"
                :label="shop.name"
                :value="shop.id"
              />
            </el-select>
          </div>
        </div>
  
        <div v-if="selectedShop && currentShopInfo" class="selected-shop-preview">
          <el-image 
            :src="currentShopInfo.additional_info"
            :preview-src-list="[currentShopInfo.additional_info]"
            fit="cover"
            class="preview-image"
          />
        </div>
  
        <div class="review-content" v-if="selectedShop">
          <div class="rating-section">
            <span class="rating-label">评分：</span>
            <el-rate v-model="rating" />
          </div>
  
          <div class="review-text">
            <el-input
              v-model="reviewContent"
              type="textarea"
              :rows="4"
              placeholder="还记得这家店的特色吗？写下你的评价，分享体验"
            />
          </div>
  
          <div class="review-footer">
            <el-button type="primary" @click="submitReview" :disabled="!canSubmit">
              发布评价
            </el-button>
          </div>
        </div>
  
        <div class="my-reviews">
          <div class="section-divider"></div>
          <h3 class="section-title">我的评价</h3>
          
          <div class="review-list" v-if="myReviews.length > 0">
            <div v-for="review in myReviews" :key="review.id" class="review-item">
              <div class="review-shop-info">
                <span class="shop-name">{{ review.shopName }}</span>
                <span class="review-time">{{ review.time }}</span>
              </div>
              
              <div v-if="editingReviewId !== review.id">
                <div class="review-rating">
                  <el-rate
                    v-model="review.rating"
                    disabled
                    show-score
                    text-color="#ff9f1c"
                  />
                </div>
                <div class="review-text-content">{{ review.content }}</div>
                <div class="review-actions">
                  <el-button type="text" size="small" @click="startEdit(review)">
                    编辑
                  </el-button>
                  <el-button type="text" size="small" class="delete-btn" @click="confirmDelete(review)">
                    删除
                  </el-button>
                </div>
              </div>
              <div v-else class="edit-form">
                <el-input
                  v-model="editingContent"
                  type="textarea"
                  :rows="3"
                  placeholder="编辑您的评价"
                />
                <div class="edit-actions">
                  <el-button size="small" @click="cancelEdit">取消</el-button>
                  <el-button size="small" type="primary" @click="saveEdit(review)">保存</el-button>
                  <el-button size="small" type="danger" @click="confirmDelete(review)">删除</el-button>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="empty-reviews">
            <el-empty description="暂无评价信息" />
          </div>
        </div>
      </div>
  
      <!-- 删除确认对话框 -->
      <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除"
        width="30%"
        center
      >
        <span>确定要删除这条评价吗？</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="deleteReview">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted } from 'vue'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  
  const stats = ref({
    following: 0,
    followers: 0,
    likes: 0
  })
  
  const activities = ref([
    {
      shopName: '华景山城火锅',
      action: '签到',
      time: '2025-04-21 18:55'
    },
    {
      shopName: '泰禾南向',
      action: '签到',
      time: '2024-12-14 12:51'
    },
    {
      shopName: '味味黑牛肉馆',
      action: '签到',
      time: '2024-11-12 19:10'
    },
    {
      shopName: '晋三三火锅冒菜 曾峰路',
      action: '添加了评价',
      time: '2024-11-03 12:35'
    },
    {
      shopName: '晋三三火锅冒菜 曾峰路',
      action: '签到',
      time: '2023-12-13 12:19'
    }
  ])
  
  const showReviewInput = ref(false)
  const currentShop = ref('')
  const reviewContent = ref('')
  
  const selectedShop = ref('')
  const rating = ref(0)
  const shopList = ref([])
  
  const STORAGE_KEY = 'user_reviews'
  
  // 从 localStorage 获取评价数据
  const loadReviews = () => {
    const savedReviews = localStorage.getItem(STORAGE_KEY)
    return savedReviews ? JSON.parse(savedReviews) : []
  }
  
  // 保存评价数据到 localStorage
  const saveReviews = (reviews) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(reviews))
  }
  
  const myReviews = ref(loadReviews())
  
  const fetchShopList = async () => {
    try {
      const response = await axios.get('http://localhost:3000/Huanglist2')
      shopList.value = response.data
    } catch (error) {
      console.error('获取店铺列表失败:', error)
    }
  }
  
  const canSubmit = computed(() => {
    return selectedShop.value && rating.value > 0 && reviewContent.value.trim().length > 0
  })
  
  const submitReview = async () => {
    if (!canSubmit.value) return
  
    try {
      const shopResponse = await axios.get(`http://localhost:3000/Huanglist2/${selectedShop.value}`)
      const shop = shopResponse.data
  
      // 更新店铺评分和评论数
      const updatedShop = {
        ...shop,
        reviews: shop.reviews + 1,
        rating: ((shop.rating * shop.reviews) + rating.value) / (shop.reviews + 1)
      }
  
      await axios.put(`http://localhost:3000/Huanglist2/${selectedShop.value}`, updatedShop)
  
      // 添加新评价到个人评价列表
      const newReview = {
        id: Date.now(),
        shopName: shop.name,
        content: reviewContent.value,
        rating: rating.value,
        time: new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        }).replace(/\//g, '-')
      }
      
      // 更新评价列表并保存到 localStorage
      myReviews.value.unshift(newReview)
      saveReviews(myReviews.value)
  
      ElMessage.success('评价提交成功')
      
      // 重置表单
      selectedShop.value = ''
      rating.value = 0
      reviewContent.value = ''
      
    } catch (error) {
      console.error('提交评价失败:', error)
      ElMessage.error('评价提交失败，请重试')
    }
  }
  
  // 编辑相关的状态
  const editingReviewId = ref(null)
  const editingContent = ref('')
  const deleteDialogVisible = ref(false)
  const reviewToDelete = ref(null)
  
  // 开始编辑
  const startEdit = (review) => {
    editingReviewId.value = review.id
    editingContent.value = review.content
  }
  
  // 取消编辑
  const cancelEdit = () => {
    editingReviewId.value = null
    editingContent.value = ''
  }
  
  // 保存编辑
  const saveEdit = async (review) => {
    if (!editingContent.value.trim()) {
      ElMessage.warning('评价内容不能为空')
      return
    }
  
    const updatedReviews = myReviews.value.map(r => {
      if (r.id === review.id) {
        return {
          ...r,
          content: editingContent.value,
          time: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
          }).replace(/\//g, '-') + ' (已编辑)'
        }
      }
      return r
    })
  
    myReviews.value = updatedReviews
    saveReviews(updatedReviews)
    editingReviewId.value = null
    editingContent.value = ''
    ElMessage.success('评价修改成功')
  }
  
  // 确认删除
  const confirmDelete = (review) => {
    reviewToDelete.value = review
    deleteDialogVisible.value = true
  }
  
  // 执行删除
  const deleteReview = () => {
    const updatedReviews = myReviews.value.filter(r => r.id !== reviewToDelete.value.id)
    myReviews.value = updatedReviews
    saveReviews(updatedReviews)
    deleteDialogVisible.value = false
    reviewToDelete.value = null
    ElMessage.success('评价删除成功')
  }
  
  const currentShopInfo = ref(null)
  
  // 处理店铺选择
  const handleShopSelect = async (shopId) => {
    try {
      const response = await axios.get(`http://localhost:3000/Huanglist2/${shopId}`)
      currentShopInfo.value = response.data
    } catch (error) {
      console.error('获取店铺信息失败:', error)
      ElMessage.error('获取店铺信息失败')
    }
  }
  
  onMounted(() => {
    fetchShopList()
  })
  </script>
  
  <style scoped>
  .page-container {
    display: flex;
    gap: 20px;
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
    justify-content: center;
    align-items: flex-start;
  }
  
  .user-profile {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    width: 300px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }
  
  .user-stats {
    display: flex;
    justify-content: space-around;
    padding-bottom: 15px;
    border-bottom: 1px solid #e5e5e5;
  }
  
  .stat-item {
    text-align: center;
  }
  
  .stat-value {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
  
  .stat-label {
    font-size: 14px;
    color: #666;
    margin-top: 4px;
  }
  
  .register-info {
    font-size: 12px;
    color: #999;
    padding: 15px 0;
  }
  
  .section-title {
    font-size: 16px;
    color: #333;
    font-weight: bold;
    margin: 0 0 15px 0;
  }
  
  .activity-list {
    margin-bottom: 15px;
  }
  
  .activity-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;
    font-size: 13px;
  }
  
  .activity-content {
    color: #666;
    line-height: 1.5;
    flex: 1;
    margin-right: 10px;
  }
  
  .shop-name {
    color: #06c1ae;
    cursor: pointer;
  }
  
  .shop-name:hover {
    color: #028a7c;
  }
  
  .activity-time {
    color: #999;
    font-size: 12px;
    white-space: nowrap;
  }
  
  .view-more {
    text-align: center;
    color: #666;
    font-size: 13px;
    cursor: pointer;
    padding: 10px 0;
    border-top: 1px solid #e5e5e5;
  }
  
  .view-more:hover {
    color: #06c1ae;
  }
  
  .reviews-section {
    margin-top: 20px;
  }
  
  .review-input {
    background: #f8f8f8;
    padding: 15px;
    border-radius: 4px;
  }
  
  .shop-info {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
  }
  
  .status {
    color: #999;
    font-size: 12px;
  }
  
  .review-textarea {
    margin-top: 10px;
  }
  
  :deep(.el-textarea__inner) {
    resize: none;
    border: 1px solid #e5e5e5;
  }
  
  :deep(.el-textarea__inner:focus) {
    border-color: #06c1ae;
  }
  
  .review-container {
    flex: 0 1 600px;
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }
  
  .review-header {
    margin-bottom: 20px;
    text-align: center;
  }
  
  .shop-select-input {
    width: 100%;
    max-width: 400px;
    margin: 0 auto;
  }
  
  .rating-section {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
  }
  
  .rating-label {
    margin-right: 10px;
    color: #666;
  }
  
  .review-text {
    margin-bottom: 20px;
    max-width: 100%;
  }
  
  .review-footer {
    text-align: center;
    margin-top: 20px;
  }
  
  :deep(.el-rate__icon) {
    font-size: 20px;
    margin-right: 6px;
  }
  
  :deep(.el-textarea__inner) {
    resize: none;
    border: 1px solid #e5e5e5;
  }
  
  :deep(.el-textarea__inner:focus) {
    border-color: #06c1ae;
  }
  
  :deep(.el-button--primary) {
    background-color: #ff9f1c;
    border-color: #ff9f1c;
  }
  
  :deep(.el-button--primary:hover) {
    background-color: #ffb449;
    border-color: #ffb449;
  }
  
  :deep(.el-button--primary:focus) {
    background-color: #ff9f1c;
    border-color: #ff9f1c;
  }
  
  :deep(.el-select .el-input__inner) {
    border-color: #e5e5e5;
  }
  
  :deep(.el-select .el-input__inner:focus) {
    border-color: #06c1ae;
  }
  
  .section-divider {
    height: 1px;
    background: #e5e5e5;
    margin: 30px 0 20px;
  }
  
  .review-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
    max-width: 100%;
  }
  
  .review-item {
    padding: 15px;
    background: #fff;
    border-bottom: 1px solid #e5e5e5;
    text-align: left;
  }
  
  .review-shop-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .shop-name {
    color: #06c1ae;
    font-size: 14px;
    cursor: pointer;
  }
  
  .shop-name:hover {
    color: #028a7c;
  }
  
  .review-time {
    color: #999;
    font-size: 12px;
  }
  
  .review-text-content {
    color: #666;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 30px;
  }
  
  .empty-reviews {
    padding: 40px 0;
    text-align: center;
  }
  
  :deep(.el-empty__description) {
    color: #999;
  }
  
  .review-actions {
    display: flex;
    gap: 15px;
    justify-content: flex-end;
    margin-top: 10px;
  }
  
  .edit-form {
    margin: 10px 0;
  }
  
  .edit-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 10px;
  }
  
  .delete-btn {
    color: #ff4d4f;
  }
  
  .delete-btn:hover {
    color: #ff7875;
  }
  
  :deep(.el-button--text) {
    padding: 0;
    color: #ff9f1c;
  }
  
  :deep(.el-button--text:hover) {
    color: #ffb449;
  }
  
  :deep(.el-textarea__inner) {
    margin-bottom: 10px;
  }
  
  :deep(.el-dialog__body) {
    text-align: center;
    padding: 20px;
    color: #666;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: 20px;
  }
  
  :deep(.el-dialog__footer) {
    .el-button--primary {
      background-color: #ff9f1c;
      border-color: #ff9f1c;
      
      &:hover {
        background-color: #ffb449;
        border-color: #ffb449;
      }
    }
  }
  
  .selected-shop-preview {
    margin: 15px auto;
    text-align: center;
    max-width: 240px;
  }
  
  .preview-image {
    width: 240px;
    height: 180px;
    border-radius: 6px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
  }
  
  :deep(.el-image) {
    border-radius: 6px;
    overflow: hidden;
  }
  
  :deep(.el-image__inner) {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .review-rating {
    margin: 8px 0;
  }
  
  :deep(.el-rate) {
    display: inline-block;
  }
  
  :deep(.el-rate__text) {
    color: #ff9f1c;
    font-size: 14px;
  }
  </style>